<template>
  <div class="app-container">
    <el-card>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="车抵贷导入" name="carLoan">
          <el-form ref="uploadForm" :model="carLoanForm" label-width="120px">
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-select v-model="carLoanForm.carBrand" placeholder="请选择车辆品牌" clearable class="!w-240px">
                <el-option
                  v-for="item in carBrandOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="Excel文件">
              <el-upload
                ref="carLoanUploadRef"
                v-model:file-list="carLoanFileList"
                :action="carLoanImportUrl"
                :auto-upload="false"
                :disabled="formLoading"
                :headers="uploadHeaders"
                :limit="1"
                :on-error="handleCarLoanError"
                :on-exceed="handleExceed"
                :on-success="handleCarLoanSuccess"
                accept=".xlsx, .xls"
                drag
              >
                <Icon icon="ep:upload" />
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip text-center">
                    <span>仅允许导入 xls、xlsx 格式文件。</span>
                    <el-link
                      :underline="false"
                      style="font-size: 12px; vertical-align: baseline"
                      type="primary"
                      @click="handleDownloadCarLoanTemplate"
                    >
                      下载模板
                    </el-link>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :disabled="formLoading" @click="submitCarLoanUpload">开始导入</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="信用贷导入" name="creditLoan">
          <el-form ref="uploadForm" :model="creditLoanForm" label-width="120px">
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input v-model="creditLoanForm.ipAddress" placeholder="请输入IP地址" clearable class="!w-240px" />
            </el-form-item>
            <el-form-item label="Excel文件">
              <el-upload
                ref="creditLoanUploadRef"
                v-model:file-list="creditLoanFileList"
                :action="creditLoanImportUrl"
                :auto-upload="false"
                :disabled="formLoading"
                :headers="uploadHeaders"
                :limit="1"
                :on-error="handleCreditLoanError"
                :on-exceed="handleExceed"
                :on-success="handleCreditLoanSuccess"
                accept=".xlsx, .xls"
                drag
              >
                <Icon icon="ep:upload" />
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip text-center">
                    <span>仅允许导入 xls、xlsx 格式文件。</span>
                    <el-link
                      :underline="false"
                      style="font-size: 12px; vertical-align: baseline"
                      type="primary"
                      @click="handleDownloadCreditLoanTemplate"
                    >
                      下载模板
                    </el-link>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :disabled="formLoading" @click="submitCreditLoanUpload">开始导入</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="公积金导入" name="houseFund">
          <el-form ref="uploadForm" :model="houseFundForm" label-width="120px">
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input v-model="houseFundForm.ipAddress" placeholder="请输入IP地址" clearable class="!w-240px" />
            </el-form-item>
            <el-form-item label="Excel文件">
              <el-upload
                ref="houseFundUploadRef"
                v-model:file-list="houseFundFileList"
                :action="houseFundImportUrl"
                :auto-upload="false"
                :disabled="formLoading"
                :headers="uploadHeaders"
                :limit="1"
                :on-error="handleHouseFundError"
                :on-exceed="handleExceed"
                :on-success="handleHouseFundSuccess"
                accept=".xlsx, .xls"
                drag
              >
                <Icon icon="ep:upload" />
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip text-center">
                    <span>仅允许导入 xls、xlsx 格式文件。</span>
                    <el-link
                      :underline="false"
                      style="font-size: 12px; vertical-align: baseline"
                      type="primary"
                      @click="handleDownloadHouseFundTemplate"
                    >
                      下载模板
                    </el-link>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :disabled="formLoading" @click="submitHouseFundUpload">开始导入</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 导入结果对话框 -->
    <el-dialog v-model="importResultVisible" title="导入结果" width="500px">
      <div v-if="importResult">
        <el-result
          :icon="importResult.success ? 'success' : 'error'"
          :title="importResult.success ? '导入成功' : '导入失败'"
          :sub-title="importResult.message || (importResult.success ? '数据导入成功' : '数据导入失败')"
        >
          <template #extra>
            <div v-if="importResult.success">
              <p>创建数量：{{ importResult.createCount }}</p>
              <p>更新数量：{{ importResult.updateCount }}</p>
              <p>失败数量：{{ importResult.failureCount }}</p>
            </div>
            <div v-if="importResult.failures && importResult.failures.length > 0">
              <el-collapse>
                <el-collapse-item title="失败详情">
                  <ul class="error-list">
                    <li v-for="(error, index) in importResult.failures" :key="index">
                      {{ error }}
                    </li>
                  </ul>
                </el-collapse-item>
              </el-collapse>
            </div>
          </template>
        </el-result>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import download from '@/utils/download'
import { 
  downloadCarLoanTemplate, 
  downloadCreditLoanTemplate, 
  downloadHouseFundTemplate
} from '@/api/weiyi/data'
import { getAccessToken, getTenantId } from '@/utils/auth'

defineOptions({ name: 'DataImport' })

const route = useRoute()
const activeTab = ref('carLoan')
const uploadForm = reactive({})
const importResultVisible = ref(false)
const importResult = ref<any>(null)
const formLoading = ref(false)

// 添加表单数据对象
const carLoanForm = reactive({
  carBrand: ''
})

const creditLoanForm = reactive({
  ipAddress: ''
})

const houseFundForm = reactive({
  ipAddress: ''
})

// 车辆品牌选项
const carBrandOptions = ref([
  { value: 'audi', label: '奥迪' },
  { value: 'bmw', label: '宝马' },
  { value: 'benz', label: '奔驰' },
  { value: 'toyota', label: '丰田' },
  { value: 'honda', label: '本田' },
  { value: 'nissan', label: '日产' },
  { value: 'ford', label: '福特' },
  { value: 'chevrolet', label: '雪佛兰' },
  { value: 'volkswagen', label: '大众' },
  { value: 'hyundai', label: '现代' }
])

// 上传URL
const carLoanImportUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/weiyi/data-import/car-loan/import'
const creditLoanImportUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/weiyi/data-import/credit-loan/import'
const houseFundImportUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/weiyi/data-import/house-fund/import'

// 上传 Header 头
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})

// 文件列表
const carLoanFileList = ref([])
const creditLoanFileList = ref([])
const houseFundFileList = ref([])

// 上传组件引用
const carLoanUploadRef = ref()
const creditLoanUploadRef = ref()
const houseFundUploadRef = ref()

// 文件数超出提示
const handleExceed = (): void => {
  ElMessage.warning('最多只能上传一个文件！')
}

// 处理上传成功
const handleCarLoanSuccess = (response) => {
  if (response.code === 0) {
    importResult.value = response.data
    importResultVisible.value = true
    ElMessage.success('导入成功')
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
  // 重置请求头
  delete uploadHeaders.value['car-brand']
  formLoading.value = false
}

const handleCreditLoanSuccess = (response) => {
  if (response.code === 0) {
    importResult.value = response.data
    importResultVisible.value = true
    ElMessage.success('导入成功')
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
  // 重置请求头
  delete uploadHeaders.value['ip-address']
  formLoading.value = false
}

const handleHouseFundSuccess = (response) => {
  if (response.code === 0) {
    importResult.value = response.data
    importResultVisible.value = true
    ElMessage.success('导入成功')
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
  // 重置请求头
  delete uploadHeaders.value['ip-address']
  formLoading.value = false
}

// 处理上传失败
const handleCarLoanError = () => {
  ElMessage.error('上传失败，请检查网络连接或联系管理员')
  // 重置请求头
  delete uploadHeaders.value['car-brand']
  formLoading.value = false
}

const handleCreditLoanError = () => {
  ElMessage.error('上传失败，请检查网络连接或联系管理员')
  // 重置请求头
  delete uploadHeaders.value['ip-address']
  formLoading.value = false
}

const handleHouseFundError = () => {
  ElMessage.error('上传失败，请检查网络连接或联系管理员')
  // 重置请求头
  delete uploadHeaders.value['ip-address']
  formLoading.value = false
}

// 提交上传
const submitCarLoanUpload = async () => {
  if (carLoanFileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的文件')
    return
  }
  
  if (!carLoanForm.carBrand) {
    ElMessage.warning('请选择车辆品牌')
    return
  }
  
  formLoading.value = true
  // 添加车辆品牌到请求头
  uploadHeaders.value['car-brand'] = carLoanForm.carBrand
  carLoanUploadRef.value.submit()
}

const submitCreditLoanUpload = async () => {
  if (creditLoanFileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的文件')
    return
  }
  
  if (!creditLoanForm.ipAddress) {
    ElMessage.warning('请输入IP地址')
    return
  }
  
  formLoading.value = true
  // 添加IP地址到请求头
  uploadHeaders.value['ip-address'] = creditLoanForm.ipAddress
  creditLoanUploadRef.value.submit()
}

const submitHouseFundUpload = async () => {
  if (houseFundFileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的文件')
    return
  }
  
  if (!houseFundForm.ipAddress) {
    ElMessage.warning('请输入IP地址')
    return
  }
  
  formLoading.value = true
  // 添加IP地址到请求头
  uploadHeaders.value['ip-address'] = houseFundForm.ipAddress
  houseFundUploadRef.value.submit()
}

// 下载模板
const handleDownloadCarLoanTemplate = async () => {
  try {
    const res = await downloadCarLoanTemplate()
    download.excel(res, '车抵贷导入模板.xlsx')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  }
}

const handleDownloadCreditLoanTemplate = async () => {
  try {
    const res = await downloadCreditLoanTemplate()
    download.excel(res, '信用贷导入模板.xlsx')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  }
}

const handleDownloadHouseFundTemplate = async () => {
  try {
    const res = await downloadHouseFundTemplate()
    download.excel(res, '公积金导入模板.xlsx')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  }
}

/** 初始化 **/
onMounted(() => {
  // 从URL参数中获取标签页
  const tabParam = route.query.tab as string
  if (tabParam && ['carLoan', 'creditLoan', 'houseFund'].includes(tabParam)) {
    activeTab.value = tabParam
  }
})
</script>

<style scoped>
.error-list {
  max-height: 200px;
  padding-left: 20px;
  overflow-y: auto;
}
</style> 